import { NextRequest, NextResponse } from 'next/server';
import { templateImportService } from '@/lib/template-import';
import { verifyAuth } from '@/lib/auth-middleware';

export async function POST(request: NextRequest) {
  try {
    console.log('=== 数据导入API调用开始 ===');
    
    const authResult = await verifyAuth();
    if (!authResult.success || !authResult.user) {
      console.log('认证失败:', authResult.error);
      return NextResponse.json({ 
        success: false, 
        error: authResult.error || '未登录' 
      }, { status: authResult.status || 401 });
    }
    
    const user = authResult.user;
    console.log('用户认证成功:', user.username, user.role_code);

    const formData = await request.formData();
    const file = formData.get('file') as File;
    const specialty = formData.get('specialty') as string;
    const objectCategory = formData.get('objectCategory') as string;
    const classificationCode = formData.get('classificationCode') as string;
    const validateOnly = formData.get('validateOnly') === 'true';
    const skipDuplicates = formData.get('skipDuplicates') === 'true';
    
    console.log('请求参数:', {
      fileName: file?.name,
      fileSize: file?.size,
      specialty,
      objectCategory,
      classificationCode,
      validateOnly,
      skipDuplicates,
      userRole: user.role_code
    });

    if (!file) {
      return NextResponse.json({
        success: false,
        error: '请选择要导入的文件'
      }, { status: 400 });
    }

    if (!specialty || !objectCategory) {
      return NextResponse.json({
        success: false,
        error: '缺少专业或对象类信息'
      }, { status: 400 });
    }

    // 验证文件格式
    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
      return NextResponse.json({
        success: false,
        error: '不支持的文件格式，请上传Excel文件'
      }, { status: 400 });
    }

    // 获取文件内容
    const buffer = await file.arrayBuffer();
    console.log('文件内容已读取，大小:', buffer.byteLength);

    // 执行导入
    console.log('开始执行模板导入服务...');
    const result = await templateImportService.importTemplateData(buffer, {
      specialty,
      objectCategory,
      classificationCode: classificationCode || undefined,
      userRole: user.role_code || 'V',
      validateOnly,
      skipDuplicates
    });

    console.log('导入服务执行完成，结果:', {
      success: result.success,
      totalRows: result.totalRows,
      successRows: result.successRows,
      errorRows: result.errorRows
    });

    return NextResponse.json({
      success: true,
      data: result
    });

  } catch (error) {
    console.error('数据导入失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '导入失败'
    }, { status: 500 });
  }
}

// 获取导入历史记录
export async function GET(request: NextRequest) {
  try {
    const authResult = await verifyAuth();
    if (!authResult.success || !authResult.user) {
      return NextResponse.json({ 
        success: false, 
        error: authResult.error || '未登录' 
      }, { status: authResult.status || 401 });
    }
    
    const user = authResult.user;

    const { searchParams } = new URL(request.url);
    const specialty = searchParams.get('specialty');
    const classificationCode = searchParams.get('classificationCode');

    // 这里可以添加获取导入历史的逻辑
    // 暂时返回空数组
    return NextResponse.json({
      success: true,
      data: {
        imports: [],
        totalImports: 0,
        lastImportTime: null
      }
    });

  } catch (error) {
    console.error('获取导入历史失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '获取导入历史失败'
    }, { status: 500 });
  }
}